﻿CREATE PROCEDURE [dbo].[select_storehouse]
	@in_year int,
	@in_month_from int,
	@in_month_to int
AS
	declare @result_table table(result_id bigint identity(1,1) primary key,
								result_customer nvarchar(20) not null,
								result_month int not null,
								result_in decimal(5,1) default(0),
								result_out decimal(5,1) default(0),
								result_rest decimal(5,1) default(0));
	declare @customer nvarchar(20);
	declare @weight_in decimal(5,1);
	declare @weight_out decimal(5,1);
	declare @weight_rest decimal(5,1);
	
	declare @current_month int;
	set @current_month = @in_month_from;
	while @current_month <= @in_month_to begin
	
		declare customer_cursor cursor for
		select distinct inout_customer from tb_inout;
		open customer_cursor;
		fetch next from customer_cursor into @customer;
		while @@fetch_status = 0 begin
		
			select @weight_in = isnull(sum(inout_in),0) from tb_inout
			where inout_customer = @customer;
			
			select @weight_out = isnull(sum(inout_out),0) from tb_inout
			where inout_customer = @customer;
		
			set @weight_rest = @weight_in - @weight_out;		
		
			select @weight_in = isnull(sum(inout_in),0) from tb_inout
			where inout_customer = @customer and month(inout_date) = @current_month and
			year(inout_date) = @in_year;
			
			select @weight_out = isnull(sum(inout_out),0) from tb_inout
			where inout_customer = @customer and month(inout_date) = @current_month and
			year(inout_date) = @in_year;
			
			insert into @result_table(result_customer,result_month,result_in,
			result_out,result_rest) values (@customer,@current_month,@weight_in,
			@weight_out,@weight_rest);
		
			fetch next from customer_cursor into @customer;
		end
		
		close customer_cursor;
		deallocate customer_cursor;
		
		set @current_month = @current_month + 1;
	
	end
	
	select * from @result_table;